import { defineStore } from 'pinia';
// import { useWsStore } from './ws';
import type { RouteRecordRaw } from 'vue-router';
import { store } from '@/store';
import { ACCESS_TOKEN, APP_USER, APP_DEPT } from '@/enums/cacheEnum';
import { Storage } from '@/utils/Storage';
import { generatorDynamicRouter } from '@/router/generator-router';
import { resetRouter } from '@/router';
import { generateMenus, filterHideMenu } from '@/router/asyncMenus';
import { isLogin, login, logout } from '@/api/account/account'

// 用户信息定义
interface UserState {
  token: string;
  name: string;
  avatar: string;
  // like [ 'sys:user:add', 'sys:user:update' ]
  perms: string[];
  // menus: RouteRecordRaw[];
  menus: RouteRecordRaw[];
  userInfo: Partial<API.AdminUserInfo>;
  // powerUser: any;
  powerUser: API.PowerUser;
  powerDept: API.PowerDept;
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    token: Storage.Get(ACCESS_TOKEN),
    name: 'amdin',
    avatar: '',
    perms: [],
    menus: [],
    userInfo: {},
    powerUser: Storage.Get(APP_USER) as API.PowerUser,
    powerDept: Storage.Get(APP_DEPT) as API.PowerDept,
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getName(): string {
      return this.name;
    },
    getPerms(): string[] {
      return this.perms;
    },
  },
  actions: {
    /** 清空token及用户信息 */
    resetToken() {
      this.avatar = this.token = this.name = '';
      this.perms = [];
      this.menus = [];
      this.userInfo = {};
      Storage.clear();
    },
    // 校验是否登录
    async isLogin() {
      const res = await isLogin()
      const data:Boolean = res.data
      return Promise.resolve({data})
    },
    // todo 登录成功设置token
    setToken(token: string) {
      this.token = token ?? '';
      Storage.Set(ACCESS_TOKEN, this.token);
    },
    // 登录成功设置用户信息
    setUserInfo(userInfo: API.PowerUser) {
      this.powerUser = userInfo;
      // this.perms = userInfo.perms;
      Storage.Set(APP_USER, userInfo);
    },
    // todo 登录方法
    async login(params: API.LoginParams) {
      try {
        const { data } = await login(params);
        // 缓存token
        this.setToken(data.token);
        // 缓存用户信息
        this.setUserInfo(data.userInfo)
        // Storage.Set(APP_USER, data.userInfo);
        // console.log('登录成功', this.token, this.powerUser)
        return this.afterLogin();
      } catch (error) {
        return Promise.reject(error);
      }
    },
    // todo 登录成功之后, 获取用户信息以及生成权限路由
    async afterLogin() {
      try {
        // todo websocket 踢人
        // const wsStore = useWsStore();
        // 动态查询菜单
        // console.log('开始调用')
        const result = await generateMenus() // 动态菜单转换结果
        const asyncMenus: API.Menu[] = result.menuList // 动态菜单
        // 注册动态路由
        const generatorResult = await generatorDynamicRouter(result.menuList);
        // 系统菜单, 更加hideInMenu 属性过滤掉静态路由隐藏参数 如home、404
        this.menus = generatorResult.menus.filter((item) => {
          if (result.hideMenu.includes(item.path)) {
            return false;
          }
          if (!item.meta?.hideInMenu) {
            return true;
          }
        });
        // console.log('渲染菜单', this.menus, result.hideMenu)
        // 注册完把隐藏的菜单删除, 过滤掉动态路由中的隐藏菜单, 如查看编辑
        this.menus = filterHideMenu(this.menus, result.hideMenu)

        ///// !wsStore.client && wsStore.initSocket();
        return { asyncMenus };
      } catch (error) {
        return Promise.reject(error);
        // return this.logout();
      }
    },
    /** 登出 */
    async logout() {
      await logout();
      // const wsStore = useWsStore();
      // wsStore.closeSocket();
      this.resetToken();
      resetRouter();
    },
  },
});

// 在组件setup函数外使用
export function useUserStoreWithOut() {
  return useUserStore(store);
}
